<script setup>
import { fetchNoticeList, fetchUnreadCount } from '@/api/notice';
import { fetchCurrentPeriods, fetchReportList } from '@/api/report';
import AppSidebar from '@/components/common/AppSidebar.vue';
import regionCodeData from '@/constants/yunnan_region_code.json';
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
// 导入ECharts
import * as echarts from 'echarts';

// initialize router
const router = useRouter();

// enterprise information
const enterpriseName = ref('');
const enterpriseRegion = ref('');
const username = ref('');

// date and greeting
const currentDate = ref('');
const greeting = ref('');

// periods
const currentPeriods = ref([]);
const periodsLoading = ref(false);

// notices
const notices = ref([]);
const noticesLoading = ref(false);

// 人数变化图表相关
const personnelChartRef = ref(null);
const personnelChart = ref(null);
const personnelData = ref([]);
const chartLoading = ref(false);

// 进度环计算
const circleRadius = 36;
const circleCircumference = 2 * Math.PI * circleRadius;

/**
 * 计算剩余天数对应的进度环偏移
 */
const getDashOffset = (daysLeft) => {
    const period = currentPeriods.value?.[0];
    if (!period) return circleCircumference;

    const start = new Date(period.period_start_time);
    const end = new Date(period.period_end_time);
    const totalDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24));

    if (!totalDays || totalDays <= 0) return circleCircumference;

    const clamped = Math.min(Math.max(daysLeft || 0, 0), totalDays);
    const progress = clamped / totalDays;
    return circleCircumference * (1 - progress);
};

/**
 * 获取问候语（根据当前时间）
 */
const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return '上午好';
    if (hour < 18) return '下午好';
    return '晚上好';
};

/**
 * 根据地区代码查找完整的地区名称
 */
const getRegionNameByCode = (code) => {
    if (!code) return '未设置地区';

    const findRegion = (data, targetCode) => {
        for (const region of data) {
            if (region.code === targetCode) {
                return region;
            }
            if (region.children && region.children.length > 0) {
                const found = findRegion(region.children, targetCode);
                if (found) return found;
            }
        }
        return null;
    };

    const region = findRegion(regionCodeData, Number(code));

    if (!region) {
        return `地区代码: ${code}`;
    }

    if (region.parentId) {
        const parent = findRegion(regionCodeData, region.parentId);
        if (parent && parent.parentId) {
            const grandParent = findRegion(regionCodeData, parent.parentId);
            if (grandParent) {
                return `${grandParent.name} · ${parent.name} · ${region.name}`;
            }
            return `${parent.name} · ${region.name}`;
        }
        return parent ? `${parent.name} · ${region.name}` : region.name;
    }

    return region.name;
};

/**
 * 格式化日期为中文格式
 */
const formatDate = () => {
    const now = new Date();
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    const weekDay = weekDays[now.getDay()];
    return `${year}年${month}月${day}日 ${weekDay}`;
};

/**
 * 格式化调查期时间范围
 */
const formatPeriodTime = (startTime, endTime) => {
    const formatSingleDate = (dateInput) => {
        let date;
        if (typeof dateInput === 'number' || typeof dateInput === 'string') {
            date = new Date(dateInput);
        } else if (dateInput instanceof Date) {
            date = dateInput;
        } else {
            return '--.--';
        }

        if (isNaN(date.getTime())) return '--.--';

        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${month}.${day}`;
    };

    return `${formatSingleDate(startTime)} - ${formatSingleDate(endTime)}`;
};

/**
 * 计算距离截止日期还有多少天
 */
const calculateDaysLeft = (endTime) => {
    let end;
    if (typeof endTime === 'number' || typeof endTime === 'string') {
        end = new Date(endTime);
    } else if (endTime instanceof Date) {
        end = endTime;
    } else {
        return 0;
    }

    if (isNaN(end.getTime())) return 0;

    const now = new Date();
    const diff = end - now;
    const days = Math.ceil(diff / (1000 * 60 * 60 * 24));

    return days > 0 ? days : 0;
};

/**
 * 加载企业信息
 */
const loadEnterpriseInfo = () => {
    try {
        const enterpriseInfoStr = localStorage.getItem('enterpriseInfo');
        const usernameStr = localStorage.getItem('username');

        if (enterpriseInfoStr) {
            const info = JSON.parse(enterpriseInfoStr);
            enterpriseName.value = info.name || info.enterpriseName || '企业用户';

            const regionCode = info.region || info.regionCode || info.address;
            if (regionCode) {
                enterpriseRegion.value = getRegionNameByCode(regionCode);
            } else {
                enterpriseRegion.value = '未设置地区';
            }
        } else {
            enterpriseName.value = '企业用户';
            enterpriseRegion.value = '未设置地区';
        }

        username.value = usernameStr || '';
    } catch (error) {
        console.error('加载企业信息失败:', error);
        enterpriseName.value = '企业用户';
        enterpriseRegion.value = '未设置地区';
    }
};

/**
 * 加载当前可填报的调查期
 */
const loadPeriods = async () => {
    periodsLoading.value = true;
    try {
        const data = await fetchCurrentPeriods();
        if (data && data.periods && Array.isArray(data.periods)) {
            const validPeriods = data.periods
                .map((period) => ({
                    ...period,
                    days_left: calculateDaysLeft(period.period_end_time),
                }))
                .filter((period) => period.days_left > 0);

            validPeriods.sort((a, b) => new Date(a.period_end_time) - new Date(b.period_end_time));
            currentPeriods.value = validPeriods.length > 0 ? [validPeriods[0]] : [];
        } else {
            currentPeriods.value = [];
        }
    } catch (error) {
        console.error('加载调查期失败:', error);
        currentPeriods.value = [];
    } finally {
        periodsLoading.value = false;
    }
};

/**
 * 加载最新通知公告
 */
const loadNotices = async () => {
    noticesLoading.value = true;
    try {
        const enterpriseInfoStr = localStorage.getItem('enterpriseInfo');
        let enterpriseId = '';
        if (enterpriseInfoStr) {
            const info = JSON.parse(enterpriseInfoStr);
            enterpriseId = info.id || info.enterpriseId || '';
        }

        // 先拉取首页数据并拿到分页信息
        const firstPage = await fetchNoticeList({
            enterprise_id: enterpriseId,
            page_no: 1,
            page_size: 5,
        });

        const serverPageSize = Number(firstPage?.pageSize) || 5;
        const apiTotal = Number(firstPage?.totalCount) || 0;
        const pageTotal =
            Number(firstPage?.pageTotal) ||
            (apiTotal > 0 ? Math.ceil(apiTotal / serverPageSize) : 1);

        let allNotices = Array.isArray(firstPage?.list) ? [...firstPage.list] : [];

        // 如果有多页，拉齐全部数据，避免首页通知显示不全
        if (pageTotal > 1) {
            const tasks = [];
            for (let page = 2; page <= pageTotal; page++) {
                tasks.push(
                    fetchNoticeList({
                        enterprise_id: enterpriseId,
                        page_no: page,
                        page_size: serverPageSize,
                    })
                );
            }

            const results = await Promise.allSettled(tasks);
            results.forEach((res) => {
                if (res.status === 'fulfilled' && Array.isArray(res.value?.list)) {
                    allNotices = allNotices.concat(res.value.list);
                }
            });
        }

        // 只展示最新 5 条，按发布时间排序兜底
        notices.value = allNotices
            .sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime))
            .slice(0, 5);
    } catch (error) {
        console.error('加载通知失败:', error);
        notices.value = [];
    } finally {
        noticesLoading.value = false;
    }
};

/**
 * 初始化人数变化图表
 */
const initPersonnelChart = () => {
    // 检查图表容器是否存在
    if (!personnelChartRef.value) {
        return null;
    }

    // 销毁已存在的图表实例
    if (personnelChart.value) {
        personnelChart.value.dispose();
        personnelChart.value = null;
    }

    try {
        // 创建图表实例
        personnelChart.value = echarts.init(personnelChartRef.value);
    } catch (error) {
        return null;
    }

    // 准备数据
    const data = personnelData.value;

    if (!Array.isArray(data) || data.length === 0) {
        return null;
    }

    const months = data.map((item) => item.monthLabel);
    const counts = data.map((item) => item.count);

    // 设置图表配置
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
                lineStyle: {
                    color: '#667eea',
                    width: 1,
                    type: 'dashed',
                },
            },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e0e0e0',
            borderWidth: 1,
            textStyle: {
                color: '#333',
            },
            formatter: function (params) {
                if (params && params.length > 0) {
                    const data = params[0];
                    // 格式化数字，添加千分位分隔符，确保清晰显示人数
                    const formattedCount = Number(data.value).toLocaleString('zh-CN');
                    return `${data.axisValue}<br/>人数: ${formattedCount}人`;
                }
                return '';
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '8%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            data: months,
            axisLabel: {
                interval: 0,
            },
        },
        yAxis: {
            type: 'value',
            name: '人数',
            axisLabel: {
                formatter: '{value}人',
            },
        },
        series: [
            {
                name: '就职人数',
                type: 'line',
                smooth: true,
                data: counts,
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(102, 126, 234, 0.5)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(102, 126, 234, 0.1)',
                            },
                        ],
                    },
                },
                lineStyle: {
                    width: 3,
                    color: '#667eea',
                },
                itemStyle: {
                    color: '#667eea',
                    borderColor: '#fff',
                    borderWidth: 2,
                },
                emphasis: {
                    scale: true,
                    itemStyle: {
                        shadowBlur: 10,
                        shadowColor: 'rgba(102, 126, 234, 0.5)',
                    },
                },
            },
        ],
    };

    // 应用配置
    personnelChart.value.setOption(option);

    // 添加窗口大小变化监听
    const handleResize = () => {
        console.log('🔍 窗口大小变化，调整图表大小');
        if (personnelChart.value) {
            personnelChart.value.resize();
        }
    };

    try {
        window.addEventListener('resize', handleResize);
        console.log('🔍 添加窗口大小变化监听成功');
    } catch (error) {
        console.error('❌ 添加窗口大小变化监听失败:', error);
    }

    // 保存清理函数引用
    console.log('🔍 返回handleResize函数');
    return handleResize;
};

/**
 * 加载人数变化数据
 */
const loadPersonnelData = async () => {
    chartLoading.value = true;
    try {
        // 从后端获取所有报表数据
        const reports = await fetchReportList();

        // 确保 reports 是数组
        if (!Array.isArray(reports)) {
            personnelData.value = [];
            return;
        }

        // 处理报表数据，按 reporting_period 排序并转换为图表所需格式
        const processedData = reports
            // 过滤出有 reporting_period 的报表
            .filter((report) => report.reporting_period)
            // 按 reporting_period 排序（从旧到新）
            .sort((a, b) => a.reporting_period.localeCompare(b.reporting_period))
            // 提取最近12个月的数据
            .slice(-12)
            // 转换为图表所需格式
            .map((report) => {
                // 解析 reporting_period (YYYY-MM 格式)
                const [year, month] = report.reporting_period.split('-');
                return {
                    month: report.reporting_period,
                    monthLabel: `${month}月`,
                    count: report.current_employees || 0,
                };
            });
        personnelData.value = processedData;

        // 初始化图表并保存resizeHandler - 增加轮询机制确保容器渲染完成
        if (!Array.isArray(personnelData.value) || personnelData.value.length === 0) {
            return;
        }
        const tryInitChart = () => {
            if (personnelChartRef.value) {
                resizeHandler = initPersonnelChart();
            } else {
                // 最多重试10次，每次间隔200ms
                if (window.chartInitRetryCount === undefined) window.chartInitRetryCount = 0;
                if (window.chartInitRetryCount < 10) {
                    window.chartInitRetryCount++;
                    setTimeout(tryInitChart, 200);
                } else {
                    resizeHandler = initPersonnelChart();
                    delete window.chartInitRetryCount;
                }
            }
        };

        // 先尝试立即初始化
        if (personnelChartRef.value) {
            resizeHandler = initPersonnelChart();
        } else {
            // 延迟一小段时间后开始轮询
            setTimeout(tryInitChart, 300);
        }
    } catch (error) {
        ElMessage.error('加载人数变化数据失败');
        personnelData.value = [];
    } finally {
        chartLoading.value = false;
    }
};

const hasPersonnelData = computed(() => Array.isArray(personnelData.value) && personnelData.value.length > 0);

/**
 * 组件挂载时执行
 */
let resizeHandler = null;

onMounted(() => {
    greeting.value = getGreeting();
    currentDate.value = formatDate();
    loadEnterpriseInfo();
    Promise.all([loadPeriods(), loadNotices()]);

    // 延迟加载图表，确保DOM已经渲染
    setTimeout(() => {
        loadPersonnelData();
    }, 100);
});

/**
 * 组件卸载时清理
 */
onUnmounted(() => {
    if (resizeHandler) {
        window.removeEventListener('resize', resizeHandler);
    }
    if (personnelChart.value) {
        personnelChart.value.dispose();
    }
});

/**
 * 跳转到报表填写页面
 */
const goToReport = () => {
    if (!currentPeriods.value.length) {
        ElMessage.warning('当前没有需要填报的任务');
        return;
    }

    const period = currentPeriods.value[0];
    router.push({
        path: '/report/form',
        query: {
            period: period.investigate_time,
        },
    });
};

/**
 * 跳转到通知详情
 */
const goToNotice = (noticeId) => {
    if (!noticeId) {
        ElMessage.warning('未找到对应的通知');
        return;
    }
    router.push({
        name: 'notice-detail',
        params: { id: noticeId },
    });
};
</script>

<template>
    <div class="page-wrapper">
        <div class="home-container">
            <!-- 1. Welcome Header -->
            <div class="welcome-header">
                <div class="header-content">
                    <div class="greeting-group">
                        <h1 class="greeting-title">
                            {{ greeting }}，<span class="user-highlight">{{ enterpriseName }}</span>
                        </h1>
                        <p class="greeting-subtitle">
                            <el-icon class="header-icon">
                                <Calendar />
                            </el-icon>
                            {{ currentDate }}
                            <span class="separator">·</span>
                            <el-icon class="header-icon">
                                <Location />
                            </el-icon>
                            {{ enterpriseRegion }}
                        </p>
                    </div>
                    <div class="header-decoration">
                        <svg
                            width="300"
                            height="200"
                            viewBox="0 0 300 200"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <circle cx="250" cy="50" r="80" fill="white" fill-opacity="0.1" />
                            <circle cx="50" cy="150" r="60" fill="white" fill-opacity="0.05" />
                        </svg>
                    </div>
                </div>
            </div>

            <!-- 2. Top Row: Active Period & Notices -->
            <div class="dashboard-top-row">
                <!-- Active Period Card -->
                <div class="modern-card period-card">
                    <div class="card-header">
                        <div class="header-left">
                            <div class="header-icon-wrap blue-theme">
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="24"
                                    height="24"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                >
                                    <path
                                        d="M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5"
                                    />
                                    <path d="M16 2v4" />
                                    <path d="M8 2v4" />
                                    <path d="M3 10h5" />
                                    <path d="M17.5 17.5 16 16.25V14" />
                                    <path d="M22 16a6 6 0 1 1-12 0 6 6 0 0 1 12 0Z" />
                                </svg>
                            </div>
                            <span class="card-title">当前填报任务</span>
                        </div>
                    </div>

                    <div class="card-body">
                        <div v-if="periodsLoading" class="loading-state">
                            <el-skeleton :rows="3" animated />
                        </div>

                        <div v-else-if="currentPeriods.length > 0" class="period-content">
                            <div class="period-info">
                                <h2 class="period-name">
                                    {{ currentPeriods[0].investigate_time }} 期报表
                                </h2>
                                <div class="period-dates">
                                    <span class="label">填报周期</span>
                                    <span class="value">
                                        {{
                                            formatPeriodTime(
                                                currentPeriods[0].period_start_time,
                                                currentPeriods[0].period_end_time
                                            )
                                        }}
                                    </span>
                                </div>
                                <div class="action-buttons">
                                    <button class="action-btn" @click="goToReport">立即填报</button>
                                </div>
                            </div>

                            <div class="period-visual">
                                <div class="circle-chart">
                                    <svg viewBox="0 0 80 80" class="circular-progress">
                                        <circle cx="40" cy="40" r="36" class="bg-ring"></circle>
                                        <circle
                                            cx="40"
                                            cy="40"
                                            r="36"
                                            class="progress-ring"
                                            :stroke-dasharray="circleCircumference"
                                            :stroke-dashoffset="
                                                getDashOffset(currentPeriods[0].days_left)
                                            "
                                            transform="rotate(-90 40 40)"
                                        ></circle>
                                    </svg>
                                    <div class="circle-text">
                                        <span
                                            class="days-num"
                                            :class="{
                                                'text-urgent': currentPeriods[0].days_left <= 3,
                                            }"
                                        >
                                            {{ currentPeriods[0].days_left }}
                                        </span>
                                        <span class="days-label">天剩余</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div v-else class="empty-state">
                            <!-- <div class="empty-icon">🎉</div> -->
                            <div class="empty-text">当前没有需要填报的任务</div>
                        </div>
                    </div>
                </div>

                <!-- Notices Card -->
                <div class="modern-card notice-card">
                    <div class="card-header">
                        <div class="header-left">
                            <div class="header-icon-wrap orange-theme">
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="24"
                                    height="24"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                >
                                    <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
                                    <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
                                </svg>
                            </div>
                            <span class="card-title">通知公告</span>
                        </div>
                    </div>

                    <div class="card-body scrollable-body">
                        <div v-if="noticesLoading" class="loading-state">
                            <el-skeleton :rows="5" animated />
                        </div>

                        <div v-else-if="notices.length > 0" class="notice-list">
                            <div
                                v-for="notice in notices"
                                :key="notice.noticeId"
                                class="notice-row"
                                @click="goToNotice(notice.noticeId)"
                            >
                                <div class="notice-content">
                                    <div class="notice-top">
                                        <span v-if="notice.isImportant === 1" class="tag-important"
                                            >重要</span
                                        >
                                        <h3 class="notice-subject">
                                            {{ notice.title }}
                                        </h3>
                                    </div>
                                    <div class="notice-meta">
                                        <span>{{ notice.publisher }}</span>
                                        <span class="separator">•</span>
                                        <span>{{ notice.publishTime }}</span>
                                    </div>
                                </div>
                                <div class="notice-arrow">
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </div>
                            </div>
                        </div>

                        <div v-else class="empty-state">
                            <div class="empty-text">未找到对应的通知</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ========== 3. 底部：报表状态统计 ========== -->
            <el-card class="custom-card" shadow="hover">
                <template #header>
                    <div class="card-header-content">最近12月人数变化趋势</div>
                </template>

                <!-- 加载状态 -->
                <div v-if="chartLoading" class="loading-container">
                    <div class="loading-text">加载中...</div>
                </div>

                <!-- 图表容器 -->
                <div v-else-if="hasPersonnelData" class="chart-container">
                    <!-- 确保图表容器有明确的样式和尺寸 -->
                    <div
                        ref="personnelChartRef"
                        class="personnel-chart"
                        style="
                            width: 100%;
                            height: 400px;
                            min-width: 300px;
                            min-height: 300px;
                            background-color: #fafafa;
                            border: 1px solid #e8e8e8;
                        "
                    ></div>
                </div>

                <div v-else class="empty-state">
                    <div class="empty-text">暂无人数变化数据</div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<style scoped lang="scss">
/* ========== CSS Variables & Reset ========== */
$primary-color: #4f46e5;
$primary-hover: #4338ca;
$text-main: #1f2937;
$text-secondary: #6b7280;
$bg-page: #f8fafc;
$card-bg: #ffffff;
$shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
$shadow-md:
    0 4px 6px -1px rgb(0 0 0 / 0.1),
    0 2px 4px -2px rgb(0 0 0 / 0.1);
$shadow-hover:
    0 10px 15px -3px rgb(0 0 0 / 0.1),
    0 4px 6px -4px rgb(0 0 0 / 0.1);
$font-stack:
    'Inter',
    -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Roboto,
    'Helvetica Neue',
    Arial,
    sans-serif;

.page-wrapper {
    display: flex;
    min-height: 100vh;
    background-color: $bg-page;
    font-family: $font-stack;

    /* Override Element Plus font variable within this scope */
    --el-font-family: #{$font-stack};

    /* Ensure all children use this font */
    * {
        font-family: inherit;
    }
}

.home-container {
    flex: 1;
    padding: 32px 40px;
    max-width: 1600px;
    margin: 0 auto;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    gap: 32px;
    font-family: $font-stack;
}

/* ========== Welcome Header ========== */
.welcome-header {
    position: relative;
    background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
    border-radius: 24px;
    padding: 48px;
    overflow: hidden;
    color: white;
    box-shadow:
        0 20px 25px -5px rgb(79 70 229 / 0.15),
        0 8px 10px -6px rgb(79 70 229 / 0.15);
}

.header-content {
    position: relative;
    z-index: 2;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}

.greeting-title {
    font-size: 36px;
    font-weight: 300;
    margin: 0 0 16px 0;
    letter-spacing: -0.5px;
}

.user-highlight {
    font-weight: 700;
}

.greeting-subtitle {
    font-size: 18px;
    opacity: 0.95;
    margin: 0;
    font-weight: 400;
    display: flex;
    align-items: center;
    gap: 8px;

    .header-icon {
        font-size: 20px;
    }

    .separator {
        margin: 0 6px;
        opacity: 0.6;
    }
}

.header-decoration {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    pointer-events: none;
    z-index: 1;
}

/* ========== Layout Structure ========== */
.dashboard-top-row {
    display: grid;
    grid-template-columns: 1.2fr 1fr;
    gap: 32px;
    align-items: stretch;
}

.dashboard-bottom-row {
    width: 100%;
}

/* ========== Cards ========== */
.modern-card {
    background: white;
    border-radius: 24px;
    overflow: hidden;
    transition:
        transform 0.2s ease,
        box-shadow 0.2s ease;
    box-shadow: $shadow-md;
    border: 1px solid #f1f5f9;
    display: flex;
    flex-direction: column;

    &:hover {
        transform: translateY(-2px);
        box-shadow: $shadow-hover;
    }
}

.card-header {
    padding: 24px 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #f1f5f9;
}

.header-icon-wrap {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;

    &.blue-theme {
        background: #eff6ff;
        color: #3b82f6;
    }

    &.purple-theme {
        background: #f5f3ff;
        color: #8b5cf6;
    }

    &.orange-theme {
        background: #fff7ed;
        color: #f97316;
    }
}

.header-left {
    display: flex;
    align-items: center;
}

.card-title {
    font-size: 20px;
    font-weight: 600;
    color: $text-main;
}

.card-body {
    padding: 32px;
    flex: 1;

    &.scrollable-body {
        padding: 0;
        height: 100%;
        min-height: 400px;
    }
}

/* ========== Period Card ========== */
.period-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    height: 100%;
}

.period-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.period-name {
    font-size: 32px;
    font-weight: 700;
    color: $text-main;
    margin: 0 0 16px 0;
    letter-spacing: -0.5px;
}

.period-dates {
    display: inline-flex;
    align-items: center;
    background: #f1f5f9;
    padding: 8px 16px;
    border-radius: 10px;
    margin-bottom: 32px;
    font-size: 16px;
    width: fit-content;

    .label {
        color: $text-secondary;
        margin-right: 10px;
    }

    .value {
        color: #334155;
        font-weight: 600;
        font-size: 18px;
    }
}

.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: $primary-color;
    color: white;
    border: none;
    padding: 14px 32px;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: background 0.2s;

    &:hover {
        background: $primary-hover;
    }
}

/* Visual Countdown */
.period-visual {
    position: relative;
    width: 160px;
    height: 160px;
    flex-shrink: 0;
    margin-left: 40px;
}

.circular-progress {
    width: 100%;
    height: 100%;
    transform: rotate(0deg);
}

.bg-ring {
    fill: none;
    stroke: #f1f5f9;
    stroke-width: 8;
}

.progress-ring {
    fill: none;
    stroke: $primary-color;
    stroke-width: 8;
    stroke-linecap: round;
    transition: stroke-dashoffset 1s ease-in-out;
}

.circle-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    display: flex;
    flex-direction: column;
}

.days-num {
    font-size: 42px;
    font-weight: 700;
    color: $text-main;
    line-height: 1;

    &.text-urgent {
        color: #ef4444;
    }
}

.days-label {
    font-size: 14px;
    color: $text-secondary;
    margin-top: 4px;
}

/* ========== Notice List ========== */
.notice-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 32px;
    border-bottom: 1px solid #f1f5f9;
    cursor: pointer;
    transition: background 0.15s;

    &:hover {
        background: #f8fafc;
    }

    &:last-child {
        border-bottom: none;
    }
}

.notice-content {
    flex: 1;
    min-width: 0;
}

.notice-top {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
}

.tag-important {
    background: #fef2f2;
    color: #ef4444;
    font-size: 12px;
    padding: 3px 8px;
    border-radius: 6px;
    font-weight: 600;
    flex-shrink: 0;
}

.notice-subject {
    font-size: 16px;
    font-weight: 500;
    color: #334155;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.notice-meta {
    font-size: 14px;
    color: #94a3b8;
    display: flex;
    align-items: center;
}

/* ========== 图表容器样式 ========== */
.chart-container {
    padding: 20px;
    height: 100%;
    min-height: 400px;
}

.personnel-chart {
    width: 100%;
    height: 100%;
    min-height: 400px;
    border-radius: 8px;
}

/* ========== 加载和空状态 ========== */
.loading-container {
    text-align: center;
    padding: 80px 20px;
}

.loading-text {
    color: #86868b;
    font-size: 17px;
}

.empty-period {
    text-align: center;
    padding: 80px 20px;
    color: #86868b;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    gap: 8px;
    text-align: center;
}

.empty-icon {
    font-size: 32px;
}

.empty-text {
    font-size: 16px;
    color: #000;
    text-align: center;
}

/* ========== Responsive ========== */
@media (max-width: 1200px) {
    .dashboard-top-row {
        grid-template-columns: 1fr;
    }

    .period-content {
        flex-direction: column;
        text-align: center;
        gap: 32px;
    }

    .period-visual {
        margin-left: 0;
    }

    .period-dates {
        margin: 0 auto 24px;
    }
}

@media (max-width: 768px) {
    .home-container {
        padding: 20px;
    }

    .welcome-header {
        padding: 32px;
    }

    .greeting-title {
        font-size: 28px;
    }

    .card-title {
        font-size: 18px;
    }

    .period-name {
        font-size: 24px;
    }
}
</style>
